<?php
namespace app\common\model;

use think\model\concern\SoftDelete;;
use think\Db;
use think\Model;

class Role extends Model
{
    //软删除
    use SoftDelete;

    //定义主键
    protected $pk = 'role_id';

    //定义模型对应的表名
    protected $table = 'roles';

    //定义软删除的字段
    protected $deleteTime = 'deleted_time';

    //一个角色有多个权限，关联role_auths表
    public function auths()
    {
        return $this->hasMany('RoleAuth', 'role_id', 'role_id');
    }


    //关联manager_roles表
    //public function managers()
    //{
    //    return $this->hasMany('ManagerRole','manager_id', 'manager_id');
    //}

    public function managers()
    {
        return $this->morphTo();
    }

    protected function getManagerIdsAttr($value, $data)
    {
        return $this->managers();
    }

    protected function getModuleNameLabelAttr($value, $data)
    {
        //获取config/Auth.php中的所有配置
        $configs = config('auth.');
        $modules = array_column($configs, 'module_name_cn', 'module_name');
        if (in_array($data['module_name'], array_keys($modules))) {
            return $modules[$data['module_name']];
        }

        return '';
    }

    protected function getAuthIdsAttr($value, $data)
    {
        $result = RoleAuth::where('role_id', $data['role_id'])->column('auth_id');

        return $result;
    }

    protected function getTableIdLabelAttr($value, $data)
    {
        switch ($data['module_name']) {
            case 'platform':
                $platform = Platform::where('id', $data['table_id'])->find();
                if (empty($platform)) {
                    return '平台';
                }
                $name = $platform['name'];
                break;

            case 'channel' :
                $channel = Channel::where('id', $data['table_id'])->find();
                if (empty($channel)) {
                    return '渠道';
                }
                $name = $channel['name'];
                break;
            default :
                $name = '总后台';
                break;
        }

        return $name;
    }

}